// RequestJs.js
// JireClient.js
// jQuery.js
// SyncTicketStatus.js
class DeveloperRarcel
{
    constructor()
    {
        this.Jira = new JiraClient(this.getConfig());
        this.syncTicketStatus = new SyncTicketStatus(this.getConfig());
    }

    getConfig()
    {
        let options = {};
        try {
            let config = JSON.parse(localStorage.getItem('config'));
            options = config.target;
            if (options.url) {
                options.host = options.url;
            }
        } catch (e) {
            console.error('Something wrong with config', e);
            alert('Something wrong with config, see console have detail.');
        }

        return options;
    }

    async getDevelopers(issueKey)
    {
        let jql = 'type in(Bug,Task) AND (summary ~' + issueKey + ' AND summary !~ "\\\\[RC\\\\]")';
        let developers = [];

        let searchPromise = await this.Jira.search(jql).then(resp => resp.json()).then(function(result){
            if (result.total) {
                result.issues.forEach(function(issue) {
                    developers.push({
                        key: issue.key,
                        type: issue.fields.issuetype.name,
                        assignee: issue.fields.assignee?.displayName,
                        fixVersions: issue.fields.fixVersions,
                        status: issue.fields.status.name,
                        parentIssueKey: issue.fields.issuelinks[0]?.inwardIssue?.key,
                        parentIssueType: issue.fields.issuelinks[0]?.inwardIssue?.fields?.issuetype?.name
                    });
                });
            }
        });

        return developers;
    }

    async updateStatus(issueKey, status, type)
    {
        this.syncTicketStatus.syncTicketStatus(issueKey, status, type);
    }

    async renderAssignee(issueKey, xpath)
    {
        let self = this;

        if (!xpath) {
            xpath = '#peopledetails';
        }

        let html = '';
        jQuery('#sc-watiging').remove();
        jQuery(xpath).append('<dl id="sc-watiging"><dt><label style="color:red;">Loading SC Developer...</label></dt></dl>');

        try {
            let developers = await self.getDevelopers(issueKey);
            console.log('developers:', developers);
            developers.forEach(function(dev){
                html += '<tr style="color:blue;">';
                html += '<td>' + dev.assignee + '</td>';
                html += '</tr>';
                html += '<tr><td><a href="' + self.getRightUrl(self.getComposeUrl(self.Jira.host) + '/browse/' + dev.key) + '" target="_bank">' + dev.key + ' --> ' + dev.type + ' --> ' + dev.status + '</a>';
                html += '<button id="sync-sc-developer-done" data-t-key="' + dev.key + '" data-t-type="' + dev.type + '" data-s-key="' + dev.parentIssueKey +'" data-s-type="' + dev.parentIssueType +'">Done</button>';
                html += '</td></tr>';
            });

            html = '<dl id="sc-watiging"><dt><label style="color:red;">SC Developer</label></dt>' +
                '<dd style="width: 300px;"><table><tbody>' + html +'<tr><td>&nbsp;</td></tr></tbody><table></dd></dl>';
            jQuery('#sc-watiging').remove();
            jQuery(xpath).append(html);

            jQuery('#sync-sc-developer').off('click');
            jQuery('#sync-sc-developer').on('click', function(){
                self.renderAssignee(jQuery('#key-val').text(), '#peopledetails');
            });

            jQuery('#sync-sc-developer-done').off('click');
            jQuery('#sync-sc-developer-done').on('click', function(){
                let tKey = jQuery(this).data('t-key');
                let sKey = jQuery(this).data('s-key');
                let tType = jQuery(this).data('t-type');
                let sType = jQuery(this).data('s-type');
                self.updateStatus(tKey, 'Done', tType);
                self.updateStatus(sKey, 'Resolve Issue', sType);
                jQuery('#sc-watiging').remove();
                jQuery(xpath).append('<dl id="sc-watiging"><dt><label style="color:red;">SC Developer</label></dt><dd><table><tbody><tr><td>&nbsp;</td></tr></tbody></table></dd></dl>');
                self.renderAssignee(sKey, '#peopledetails');
            });
        } catch (e) {
            jQuery('#sc-watiging').remove();
            jQuery(xpath).append('<dl id="sc-watiging"><dt><label style="color:red;">Loading SC Developer</label></dt><dd style="color:red;">load Fail: ' + e + '</dd></dl>');
            //alert('try fetch developer info from SC Jira with error, ' + e);
        }
    }

    init()
    {
        let self = this;
        self.renderAssignee(jQuery('#key-val').text(), '#peopledetails');
        jQuery('.aui-header-primary ul.aui-nav').append('<li><button id="sync-sc-developer">fetch Developer</button></li>');
    }

    getComposeUrl(url) {
        let preg = new RegExp(/localhost/);
        let isLocal = preg.test(url);
        if (isLocal) {
            url = this.composeUrlFromParams(url);
        }
        return url;
    }

    composeUrlFromParams(inputUrl) {
        try {
            // 创建URL对象解析输入(自动处理编码问题)
            const urlObj = new URL(inputUrl);
            const params = new URLSearchParams(urlObj.search);

            // 参数存在性校验
            if (!params.has('host')) {
                console.warn('URL中缺少host参数');
                return null;
            }

            // 获取并解码参数值
            const host = decodeURIComponent(params.get('host'));
            let uri = '';
            if (params.has('uri')) {
                uri = decodeURIComponent(params.get('uri'));
            }

            // 规范化URI格式(确保以/开头)
            const normalizedUri = uri.startsWith('/') ? uri : `/${uri}`;

            // 验证host格式
            if (!/^https?:\/\//i.test(host)) {
                throw new Error('host参数必须包含协议头(http/https)');
            }

            // 组成新URL并验证有效性
            const newUrl = new URL(normalizedUri, host).href;
            return newUrl;
        } catch (e) {
            console.error('URL处理错误:', e.message);
            return null;
        }
    }

    getRightUrl($url)
    {
        let urlObj = new URL($url);
        let pathname = urlObj.pathname.replace(/\/\//g, '/');
        return urlObj. origin + pathname + urlObj.search;
    }
}
var develoeprObject = new DeveloperRarcel();
develoeprObject.init();

develoeprObject.syncTicketStatus.mapping = {
    Support: [
        "Start Progress",
        "Solution Design",
        "Start Support",
        "Waiting for Reply to Customer",
        "Resolve Issue"
    ],
    Task: [
        'To Do',
        'In Progress',
        'Done'
    ]
};
